<!-- 计划转生产委外 -->
<template>
  <pageHeader
    title="创建产品委外"
    :breadCrumb="['工厂建模', '生产BOM管理', '创建产品委外']"
    :show-back="true"
  >
    <template #footer>
      <a-space :size="20">
        <a-button @click="router.back()">取消</a-button>
        <a-button type="primary" @click="handleOk">提交</a-button>
      </a-space></template
    >
    <a-spin :loading="loading" class="cantainer">
      <!-- <div class="tab">生产工单信息</div> -->
      <TitleBox title="生产工单信息"></TitleBox>
      <div class="orderBox">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="任务单编号:">
              <a-typography-text>
                {{ form.list.taskNumber }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="关联计划编号:">
              <a-typography-text>
                {{ form.list.planNumber }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="物料编码:">
              <a-typography-text>
                {{ form.list.productNumber }}
              </a-typography-text>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="物料名称:">
              <a-typography-text>
                {{ form.list.productName }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="规格型号:">
              <a-typography-text>
                {{ form.list.productSpec }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="生产数量:">
              <a-typography-text>
                {{ form.list.taskamount }}
              </a-typography-text>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="紧急程度:">
              <a-typography-text> {{ '委外' }} </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工艺路线:">
              <a-typography-text>
                {{ form.list.routerName }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="生产BOM:">
              <a-typography-text>
                {{ dayjs(form.list.startDate).format('YYYY 年 MM 月') }}
              </a-typography-text>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      <!-- <div class="tab">委外加工要求</div> -->
      <TitleBox title="委外加工要求"></TitleBox>
      <a-form :model="form.list" ref="formRef" auto-label-width>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="外发工序"
              field="processIds"
              required
              label-col-flex="100px"
              :rules="[{ required: true, message: '外发工序是必选项！' }]"
            >
              <a-select
                v-model="form.list.processIds"
                multiple
                :style="{ width: '320px' }"
                placeholder="请选择 ..."
                allow-clear
                @change="selectProcessGroups"
              >
                <a-option
                  v-for="item in processGroup"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.sort }} \ {{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="交回工序"
              label-col-flex="100px"
              field="finishId"
              required
              :rules="[{ required: true, message: '交回工序是必选项！' }]"
            >
              <a-select
                :style="{ width: '320px' }"
                placeholder="请选择 ..."
                @change="selectFinishGroups"
                v-model="form.list.finishId"
              >
                <a-option
                  v-for="item in processGroup"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.sort }} \ {{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="交回工序产物"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                disabled
                v-model="form.list.finishManagementName"
                placeholder=""
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="产品编码"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.semifinishedArticlesNumber"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="产品名称"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.semifinishedArticlesName"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="产品规格"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.semifinishedArticlesSpec"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="供应商"
              label-col-flex="100px"
            >
              <a-select
                v-model="form.list.supplierId"
                :style="{ width: '320px' }"
                placeholder="请选择 ..."
                @change="selectSupplierInfo"
              >
                <a-option
                  v-for="item in SupplierInfo"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="已委外数量"
              label-col-flex="100px"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                disabled
                v-model="form.list.outsourcingAmount"
                placeholder="请输入委外数量"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="本次委外数量"
              field="amount"
              label-col-flex="100px"
              required
              :rules="[{ required: true, message: '本次委外数量是必填项！' }]"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                v-model="form.list.amount"
                :max="form.list.taskamount - form.list.outsourcingAmount"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              field="unitPrice"
              label="加工费(含税)"
              label-col-flex="100px"
              required
              :rules="[{ required: true, message: '加工费(含税)是必填项！' }]"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                v-model="form.list.unitPrice"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              field="rate"
              :show-colon="true"
              label="税率"
              label-col-flex="100px"
              required
              :rules="[{ required: true, message: '税率是必填项！' }]"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                v-model="form.list.rate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="含税合计"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                v-model="form.list.totalPrice"
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货人姓名"
              label-col-flex="100px"
            >
              <!-- <a-input
                :style="{ width: '320px' }"
                v-model="form.list.consigneeName"
                
              /> -->
              <a-select
                :style="{ width: '320px' }"
                placeholder="请选择 ..."
                @change="selectContactMan"
              >
                <a-option
                  v-for="item in contactManData"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货人电话"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                v-model="form.list.consigneePhone"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货地址"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                disabled
                v-model="form.list.consigneeAddress"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="委外日期"
              label-col-flex="100px"
            >
              <a-date-picker
                style="width: 330px; margin: 0 24px 24px 0"
                show-time
                :time-picker-props="{ defaultValue: '09:09:06' }"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="form.list.outsourcingDate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货日期"
              label-col-flex="100px"
            >
              <a-date-picker
                style="width: 330px; margin: 0 24px 24px 0"
                show-time
                :time-picker-props="{ defaultValue: '09:09:06' }"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="form.list.entryDate"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- <div class="tab"
        ><a-space
          ><div>附加物料清单</div
          ><a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="form.list.itemState"
            @change="EnableInventory"
          >
            <template #checked> ON </template>
            <template #unchecked> OFF </template>
          </a-switch></a-space
        >
      </div> -->
      <TitleBox title="附加物料清单">
        <template #buts
          ><a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="form.list.itemState"
            @change="EnableInventory"
          >
            <template #checked> ON </template>
            <template #unchecked> OFF </template>
          </a-switch></template
        ></TitleBox
      >
      <a-divider />
      <a-table
        :stripe="true"
        :dordered="{
          headerCell: true,
        }"
        :data="form.list.item"
        :scroll="scroll"
        :pagination="false"
      >
        <template #columns>
          <a-table-column
            title="物料编码"
            :width="100"
            align="center"
            data-index="productBomDetail.management.number"
          ></a-table-column>
          <a-table-column
            title="物料名称"
            :width="100"
            align="center"
            data-index="productBomDetail.management.name"
          ></a-table-column>
          <a-table-column title="换算率" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.dosage" /> </template
          ></a-table-column>
          <a-table-column title="规格型号" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input
                disabled
                v-model="record.productBomDetail.management.spec"
              /> </template
          ></a-table-column>
          <a-table-column title="空闲数量" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input
                disabled
                v-model="record.productBomDetail.management.freeStock"
              /> </template
          ></a-table-column>
          <a-table-column title="推荐委外数量" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input-number
                :min="1"
                v-model="record.amount"
                disabled
              /> </template
          ></a-table-column>
        </template>
      </a-table>
    </a-spin>
  </pageHeader>
</template>

<script setup lang="ts">
  import { reactive, watchEffect, ref } from 'vue';
  import _ from 'lodash';
  import {
    getOutsourcingSupplier,
    postOutsourcing,
    getProcessGroupProduct,
    getProcessGroupProductOne,
  } from '@/api/produce-management/production-operation/index';
  import { GetProductProcessRoutePage } from '@/api/FactoryModeling';
  import { GetProductIdBom } from '@/api/FactoryModeling/index';
  import { getSupplierInfo } from '@/api/buy-management/supplier-management/supplier-primary-list/index';
  import { useRoute, useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import dayjs from 'dayjs';

  const formRef = ref();
  let router = useRouter();
  let loading = ref(false);
  const form = reactive<any>({
    list: {
      item: [],
      outsourcingType: 2, // 委外类型 2:工序委外
      state: 1,
      itemState: 2,
      routerName: null,
    },
  });
  const SupplierInfo = ref([]);

  let WorkOrderHerders = [
    { code: 'workCode', name: '工单编号' },
    { code: 'bomName', name: '制造BOM' },
    { code: 'materialName', name: '产品名称' },
    { code: 'materialNumber', name: '产品编号' },
    { code: 'materialSpec', name: '规格型号' },
    { code: 'materialUnit', name: '基本单位' },
    { code: 'customerName', name: '客户名称' },
    { name: '紧急等级' }, //emergencyLevel
    { name: '结束时间' }, //endDate
    { code: 'foundName', name: '创建人' },
    { name: '物料属性' }, //materialAttribute
    { code: 'orderNumber', name: '生产订单编号' },
    { code: 'plannerName', name: '负责人名称' },
    { name: '工艺路线' },
    // { code: 'salesName', name: '销售名称' },
    { name: '开始时间' }, //startDate
  ];

  const materialData = ref([]);
  const newDosage = ref();
  const TreeData = (data: any, parentMultiplier: number) => {
    const currentMultiplier = parentMultiplier * data.dosage;
    if (!data.children) {
      return [{ ...data, dosage: currentMultiplier }];
    }
    const result: any = [];
    data.children.forEach((item: any) => {
      const childResult = TreeData(item, currentMultiplier);
      result.push(...childResult);
    });
    return result;
  };

  let formData = reactive<any>({});
  let processGroup = ref<any[]>([]);
  const loadTransferOutsourcingData = async () => {
    try {
      const transferData = JSON.parse(
        sessionStorage.getItem('TransferProcessOutsourcing') as any
      );

      Object.assign(form.list, transferData.planModel.workOrderModel.product);
      form.list = JSON.parse(
        JSON.stringify(form.list)
          .replace(/managementNumber/g, 'productNumber')
          .replace(/managementId/g, 'productId')
          .replace(/managementName/g, 'productName')
          .replace(/managementSpec/g, 'productSpec')
      );
      form.list.routerName =
        transferData.planModel.workOrderModel?.product?.productModel?.routerName;
      form.list.taskId = transferData.id;
      form.list.outsourcingAmount = transferData.outsourcingAmount;
      form.list.taskNumber = transferData.code;
      form.list.planNumber = transferData.planModel.PlanCode;
      form.list.taskamount = transferData.planTaskNumber;
      form.list.state = 1;
      const res = await GetProductIdBom({ id: form.list.productId });
      formData = res;
      const supplierInfo = await getSupplierInfo({
        id: form.list.productId,
      });
      const data = await GetProductProcessRoutePage({
        page: 1,
        size: -1,
        history: 1,
        productId: form.list.productId,
      });
      processGroup.value = data.content[0].groupData.filter(
        (i) => i.productionMethod === '委外'
      );
      processGroup.value.sort((a: any, b: any) => a.sort - b.sort);
      SupplierInfo.value = supplierInfo;
    } catch (error) {
      console.error(error);
    }
  };

  loadTransferOutsourcingData();

  watchEffect(() => {
    if (form.list.unitPrice && form.list.amount) {
      form.list.totalPrice = form.list.unitPrice * form.list.amount;
    } else if (form.list.amount && form.list.item) {
      form.list.item.forEach((item: any) => {
        item.amount = form.list.amount * item.dosage;
      });
    }
    // if(form.list.amount){

    // }
  });

  const selectProcessGroups = async (e?: number[]) => {
    if (form.list.processIds && form.list.itemState === 1) {
      form.list.semifinishedArticlesName = '';
      form.list.semifinishedArticlesNumber = '';
      form.list.semifinishedArticlesSpec = '';
      form.list.semifinishedArticlesId = null;
      form.list.item = [];
      let newArr: any = [];
      form.list.processIds.forEach((item: any) => {
        formData.productBomDetail.forEach((ele: any) => {
          ele.productGroupData.forEach((content: any) => {
            if (content.productGroupId === item)
              newArr.push({ ...ele, dosage: content.dosage });
          });
        });
      });

      newArr.forEach((ele: any) => {
        const index = form.list.item.findIndex(
          (i: any) => ele.bomId === i.bomId
        );
        if (index === -1) {
          form.list.item.push({ ...ele });
        } else {
          form.list.item[index].dosage += ele.dosage;
        }
      });

      if (form.list.amount) {
        form.list.item.forEach((item: any) => {
          item.amount = form.list.amount * item.dosage;
        });
      }

      const { managementName, managementNumber, spec, managementId } =
        await getProcessGroupProduct({
          ids: JSON.stringify(form.list.processIds),
        });

      const SelectedProcessIds = form.list.processIds
        .map((item) => processGroup.value.find((ele) => item === ele.id))
        .filter(Boolean);

      if (SelectedProcessIds.length >= 1 && SelectedProcessIds[0].sort === 1) {
        form.list.semifinishedArticlesName = managementName;
        form.list.semifinishedArticlesNumber = managementNumber;
        form.list.semifinishedArticlesSpec = spec;
        form.list.semifinishedArticlesId = managementId;
      } else if (
        SelectedProcessIds.length === 1 &&
        SelectedProcessIds[0].sort === 1
      ) {
        form.list.semifinishedArticlesName = managementName;
        form.list.semifinishedArticlesNumber = managementNumber;
        form.list.semifinishedArticlesSpec = spec;
        form.list.semifinishedArticlesId = managementId;
      } else if (
        SelectedProcessIds.length >= 1 &&
        SelectedProcessIds[0].sort !== 1
      ) {
        if (!managementId) {
          Message.warning('上一个工序未配置产出物料，请前往配置');
          router.push({ name: 'ProductProcessRoute' });
        } else {
          form.list.semifinishedArticlesName = managementName;
          form.list.semifinishedArticlesNumber = managementNumber;
          form.list.semifinishedArticlesSpec = spec;
          form.list.semifinishedArticlesId = managementId;
        }
      }
    } else {
      form.list.semifinishedArticlesName = '';
      form.list.semifinishedArticlesNumber = '';
      form.list.semifinishedArticlesSpec = '';
      form.list.semifinishedArticlesId = null;
      form.list.item = [];
      const { managementName, managementNumber, spec, managementId } =
        await getProcessGroupProduct({
          ids: JSON.stringify(form.list.processIds),
        });

      const SelectedProcessIds = form.list.processIds
        .map((item) => processGroup.value.find((ele) => item === ele.id))
        .filter(Boolean);

      if (SelectedProcessIds.length >= 1 && SelectedProcessIds[0].sort === 1) {
        form.list.semifinishedArticlesName = managementName;
        form.list.semifinishedArticlesNumber = managementNumber;
        form.list.semifinishedArticlesSpec = spec;
        form.list.semifinishedArticlesId = managementId;
      } else if (
        SelectedProcessIds.length === 1 &&
        SelectedProcessIds[0].sort === 1
      ) {
        form.list.semifinishedArticlesName = managementName;
        form.list.semifinishedArticlesNumber = managementNumber;
        form.list.semifinishedArticlesSpec = spec;
        form.list.semifinishedArticlesId = managementId;
      } else if (
        SelectedProcessIds.length >= 1 &&
        SelectedProcessIds[0].sort !== 1
      ) {
        if (!managementId) {
          Message.warning('上一个工序未配置产出物料，请前往配置');
          router.push({ name: 'ProductProcessRoute' });
        } else {
          form.list.semifinishedArticlesName = managementName;
          form.list.semifinishedArticlesNumber = managementNumber;
          form.list.semifinishedArticlesSpec = spec;
          form.list.semifinishedArticlesId = managementId;
        }
      }
    }
  };

  const contactManData = ref([]);
  const selectSupplierInfo = (e: number) => {
    if (!e) return;
    const [{ contactMan }] = SupplierInfo.value.filter((ele) => ele.id === e);
    contactManData.value = contactMan;
  };

  const selectContactMan = (e: number) => {
    const [{ phone, officeLocation, name }] = contactManData.value.filter(
      (ele) => ele.id === e
    );
    form.list.consigneePhone = phone;
    form.list.consigneeAddress = officeLocation;
    form.list.consigneeName = name;
  };

  const handleOk = () => {
    formRef.value.validate(async (res: any) => {
      if (!res) {
        if (form.list.item && form.list.itemState === 1)
          form.list.item.forEach((content) => {
            content.managementId = content.productBomDetail.management.id;
          });
        form.list.processIds = form.list.processIds.join(',');
        form.list.outsourcingDate = new Date(
          form.list.outsourcingDate
        ).toJSON();
        form.list.entryDate = new Date(form.list.entryDate).toJSON();
        form.list = JSON.parse(
          JSON.stringify(form.list)
            .replace(/semifinishedArticlesNumber/g, 'managementNumber')
            .replace(/semifinishedArticlesId/g, 'managementId')
            .replace(/semifinishedArticlesName/g, 'managementName')
            .replace(/semifinishedArticlesSpec/g, 'managementSpec')
        );
        form.list.item.forEach((item) => {
          if (
            item.productBomDetail.management.totalStock <
              item.productBomDetail.management.safetyStock ||
            !item.productBomDetail.management.totalStock
          ) {
            Message.warning(
              `${item.productBomDetail.management.name}产品的总库存量已低至安全库存量，请及时补充`
            );
          }
        });
        await postOutsourcing({ ...form.list });
        router.push({ name: 'ProcessOutsourcing' });
      }
    });
  };

  const EnableInventory = async (e: any) => {
    try {
      if (e === 1) {
        selectProcessGroups();
      } else {
        form.list.item = [];
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const selectFinishGroups = async (id: number) => {
    try {
      const { finishManagementName, finishManagementId } =
        await getProcessGroupProductOne({ id });
      if (!finishManagementId) {
        Message.warning('该工序未配置产出物料，请前往配置');
        router.push({ name: 'ProductProcessRoute' });
      }
      form.list.finishManagementName = finishManagementName;
    } catch (err: unknown) {
      console.log(err);
    }
  };
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    width: 100%;
    margin-bottom: 150px;
  }
  .form {
    padding-left: 100px;
    padding-right: 100px;
  }
  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 30px;
    font-size: 20px;
  }
  .orderBox {
    padding-left: 50px;
    // padding: 0px;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }
</style>
